<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>字典管理</title>
<meta name="decorator" content="default"/>
<script type="text/javascript">

	//url
	var listUrl = '${ctx}/sys/dictCategory/';
	var cardUrl = '${ctx}/sys/dictCategory/form';

	var currentOpt = "${opt}";
	
	//按钮状态  {状态值为 0 不可用 ；1 可用}
	var buttonStatus = {};
	buttonStatus.add 	= {add:{id:'btnAdd',st:0},edit:{id:'btnEdit',st:0},save:{id:'btnSubmit',st:1},cancel:{id:'btnCancel',st:1},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:0}};
	buttonStatus.edit	= {add:{id:'btnAdd',st:0},edit:{id:'btnEdit',st:0},save:{id:'btnSubmit',st:1},cancel:{id:'btnCancel',st:1},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:0}};
	buttonStatus.copy	= {add:{id:'btnAdd',st:0},edit:{id:'btnEdit',st:0},save:{id:'btnSubmit',st:1},cancel:{id:'btnCancel',st:1},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:0}};
	buttonStatus.save   = {add:{id:'btnAdd',st:1},edit:{id:'btnEdit',st:1},save:{id:'btnSubmit',st:0},cancel:{id:'btnCancel',st:0},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:1}};
	buttonStatus.cancel = {add:{id:'btnAdd',st:1},edit:{id:'btnEdit',st:"${not empty category.id?'1':'0'}"},save:{id:'btnSubmit',st:0},cancel:{id:'btnCancel',st:0},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:1}}
	buttonStatus.other  = {add:{id:'btnAdd',st:1},edit:{id:'btnEdit',st:"${not empty category.id?'1':'0'}"},save:{id:'btnSubmit',st:0},cancel:{id:'btnCancel',st:0},back:{id:'btnBack',st:1},copy:{id:'btnCopy',st:1}};

	$(document).ready(function() {
		//$("#name").focus();
		$("#inputForm").validate({
			submitHandler: function(form){
				loading('正在提交，请稍等...');
				form.submit();
			},
			errorContainer: "#messageBox",
			errorPlacement: function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
					error.appendTo(element.parent().parent());
				} else {
					error.insertAfter(element);
				}
			}
		});
		//updatePageStatus();
		
	});
	
	function updatePageStatus(){
		var currentOpt = "${opt}";
		if(currentOpt==null||currentOpt==''){
			currentOpt = 'other';
		}
		var btnStatus = buttonStatus[currentOpt];
		freshButtonStatus(btnStatus);
		if(currentOpt=='add' || currentOpt=='edit'){
			setTimeout('setAllPageEnable(jQuery("#formAreaId"))',1);
		}else{
			setTimeout('setAllPageDisable(jQuery("#formAreaId"))',1);
		}
		//debugger;
		if("save"==currentOpt){
			parent.refreshTree();
		}
		if('${message}'!=''){
			 alertx('${message}');
		}
		var nodeId= jQuery('[name="id"]').val();
		if(nodeId!=null && nodeId!=''){
			setTimeout('parent.selectCheckNode('+nodeId+')',1);
		}
	}
	function add(){ //新增记录
		var url = cardUrl+"?opt=add";
		url = addUrlParam(url,'parent.id',jQuery('[name="parent.id"]').val());
		window.location.href = url;
	}
	
	function copy(){
		var id = jQuery('#inputForm').find('[name="id"]').val();
		var url = cardUrl+"?opt=copy";
		url = addUrlParam(url,'id',id);
		window.location.href = url;
	}
	
	function fresh(){
		var id = jQuery('#inputForm').find('[name="id"]').val();
		var url = cardUrl;
		url = addUrlParam(url,'opt',currentOpt);
		url = addUrlParam(url,'id',id);
		window.location.href = url;
	}
	
	function edit(){ //修改记录
		var btnStatus = buttonStatus['edit'];
		freshButtonStatus(btnStatus);
		setAllPageEnable(jQuery("#formAreaId"));
		jQuery("#formAreaId").find("[name='publishstatus.id']").attr("disabled", true);
		currentOpt = 'edit';
	}
	
	function cancel(){ //取消操作
		var btnStatus = buttonStatus['cancel'];
		freshButtonStatus(btnStatus);
		setAllPageDisable(jQuery("#formAreaId"));
		jQuery('#inputForm')[0].reset();
		jQuery("#formAreaId").find(':input').each(function(){ 
			if(this.type.indexOf('select')>-1){
            	jQuery(this).select2();   //jQuery(this).select2();
            }
		});
		currentOpt = 'other';
	}
	
	function back(){ //返回
		var btnStatus = buttonStatus['other'];
		freshButtonStatus(btnStatus);
		setAllPageDisable(jQuery("#formAreaId"));
		parent.queryListPage();
	}
	
	function save(){ //保存操作
		var formObj = jQuery('#inputForm');
		var res = formObj.valid();
		if(res == true){
			var id = formObj.find('[name="id"]').val();
			var parentId = formObj.find('[name="parent.id"]').val();
			//debugger;
			if(id == parentId){
				alertx('不能选择自己作为上级权限');
				return ;
			}
			//formObj[0].submit();
			
			var result = {};
			
			var datas = formObj.serializeArray();
			
			for(var i = 0; i< datas.length; i++){
				var json = datas[i];
				var key = json.name;
				var value = json.value;
				if(key.indexOf(".")>-1){
					var ckeys = key.split(".");
					var attr = ckeys[1]
					
					var node = ckeys[0];
					var childKey = node.split("[")[0];
					var index = node.split("[")[1].split("]")[0]
					
					var childArray = result[childKey];
					if(childArray == null){
						childArray = [];
					}
					result[childKey] = childArray;
					var vo = childArray[index];
					if(vo == null){
						vo = {};
					}
					vo[attr]=value;
					childArray[index] = vo;
					
				}else{
					result[key]= value;
				}
				
			}
			if(result!=null){
				console.info("ajaxSave = ",result);
				ajaxSave(result);
				
			}
		}
	}
	
	function ajaxSave(data){
		var url = listUrl + 'ajaxSave?rk='+Math.random();
		
	    jQuery.ajax({  
			url: url, async : false,type: "POST",
			data : JSON.stringify(data),
			contentType : "application/json",  
			success: function(response) {
				info = response;
				if(info.success == '1'){
					var url2 = cardUrl;
					var id = info.id;
					url2 = addUrlParam(url2,'opt','other');
					url2 = addUrlParam(url2,'id',id);
					window.location.href = url2;
				}
				alertx(info.message);
				parent.refreshTree();
			},
			error: function(e){console.error(e);}
		});
	}
</script>
<style type="text/css">
.roleCss span{border-bottom: 0px solid #ddd;}
.roleCss label{margin-right: 10px;}
</style>
</head>
<body>
	<form:form id="inputForm" modelAttribute="category" action="${ctx}/sys/dictCategory/save" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<sys:message content="${message}"/>	
		
		<div class="breadcrumb form-search" id="toolButtonId">
			<input id="btnAdd" class="btn btn-primary" type="button" value="新 增" onclick="add()"/>&nbsp;
			<input id="btnEdit" class="btn btn-primary" type="button" value="修 改" onclick="edit()"/>&nbsp;
			<input id="btnCopy" class="btn btn-primary" type="button" value="复 制" onclick="copy()"/>&nbsp;
			<input id="btnSubmit" class="btn btn-primary" type="button" value="保 存" onclick="save()"/>&nbsp;
			<input id="btnCancel" class="btn" type="button" value="取 消" onclick="cancel()"/>
				<input id="btnFresh" class="btn" type="button" value="刷 新" onclick="fresh()"/>
			<input id="btnBack" class="btn" type="button" value="返 回" onclick="back()"/>
		</div>
		
		<div id="formAreaId">	
			<legend>业务表管理
			<span><a class="showhiddena" onclick="showArea(this,'mainFormAreaId')" name1="显示" name2="隐藏">隐藏</a> </span>
			</legend>
			<div id="mainFormAreaId">	
			<div class="control-group">
				<label class="control-label">上级：</label>
				<div class="controls">
					<%-- <form:input path="parentId" htmlEscape="false" maxlength="64" class="input-xlarge required"/> --%>
					<form:select path="parentId" class="input-xxlarge">
						<form:option value="" label="--请选择--"/>	
						<form:option value="0" label="根目录"/>
						<c:forEach items="${allCategorys}" var="item" varStatus="status">
							<form:option value="${item.id}" label="${item.name}( ${item.code})"/>
						</c:forEach>
					</form:select>
					<span class="help-inline"><font color="red">*</font> </span>
				</div>
			</div>
			<div class="control-group" style="display: ">
				<label class="control-label">编码：</label>
				<div class="controls">
					<form:input path="code" htmlEscape="false" maxlength="100" class="input-xlarge "/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">名称：</label>
				<div class="controls">
					<form:input path="name" htmlEscape="false" maxlength="100" class="input-xlarge required"/>
					<span class="help-inline"><font color="red">*</font> </span>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">描述：</label>
				<div class="controls">
					<form:textarea path="remarks" htmlEscape="false" rows="4" maxlength="256" class="input-xxlarge "/>
				</div>
			</div>
			<div class="control-group" style="display: ">
				<label class="control-label" >排序：</label>
				<div class="controls">
					<form:input path="sort" htmlEscape="false" maxlength="11" class="input-xlarge  digits"/>
				</div>
			</div>
		  </div>
			<div id="content" class="row-fluid" style="width: 100%;">
				<ul class="nav nav-tabs">
					<li class="tabli active" link="tab_childFormAreaId0"><a title="表字段">表字段</a></li>
					<span><a class="showhiddena" onclick="showArea(this,'childTabs')" name1="显示" name2="隐藏">隐藏</a> </span>
				</ul>
				<div id="childTabs" >
					<div id="tab_childFormAreaId0" refId="childFormAreaId0"></div>
				</div>
			</div>
		
			<!--<legend>课程字典
			<span><a class="showhiddena" onclick="showArea(this,'childFormAreaId0')" name1="显示" name2="隐藏">隐藏</a> </span>
			</legend>-->
			<div id="childFormAreaId0">
				<div class="breadcrumb form-search"  style="margin-bottom: 3px;height: 30px;" >&nbsp;
					<input id="btnAdd0" class="btn btn-primary" type="button" value="增 行" onclick="addCurriculumDictLine()"/>&nbsp;
					<input id="btnEdit0" class="btn btn-primary" type="button" value="编 辑" onclick="editCurriculumDictLine()"/>&nbsp;
					<input id="btnDel0" class="btn btn-primary" type="button" value="删 行" onclick="delCurriculumDictLine()"/>&nbsp;
					<input id="btnDel0" class="btn btn-primary" type="button" value="排序" onclick="sortCurriculumDictLine()"/>&nbsp;
				</div>
				<div style="width: 100%;overflow: auto;">
					<table id="contentTablecurriculumDict" class="table table-striped table-bordered table-condensed">
					<thead>
						<tr class="tableHead">
							<th style="text-align:center;" onclick="toggleCheckBox('checkboxName',this)">
					  			<input type="checkbox" checkboxName="sort" name="table_form_checkbox_all" value="">
					  		</th>
					  		<th style="text-align:center;">序号</th>
							<th>标签名</th>
							<th>值</th>
							<th>排序</th>
							<th>状态</th>
							<th>描述</th>
							<th>扩展信息</th>
							<th>备注</th>
							<th><div style="width: 100px;">操作</div></th>
						</tr>
					</thead>
					<tbody id="curriculumDictList">
									  		
					</tbody>
					</table>
				</div>		
			</div>
				<div style="height: 50px;width: 100%;"></div>
				<script type="text/template" id="curriculumDictTpl">//<!--
					<tr id="curriculumDictList{{idx}}">
						<td style="text-align:center;" >
							<input type="checkbox" name="sort" attrname="sort" value="">
							<input type="hidden" name="curriculumDictList[{{idx}}].id" attrname="id" value="{{row.id}}"/>
							<input type="hidden" name="curriculumDictList[{{idx}}].delFlag" value="{{row.delFlag}}"/>
						</td>
						<td style="text-align:center;">
							<span attrname="number">{{row.rowno}}</span>
						</td>
						<td>
							<input id="curriculumDictList{{idx}}_name" name="curriculumDictList[{{idx}}].name" type="text" value="{{row.name}}" maxlength="100" 
							class="input-small " style="" />
						</td>
						<td>
							<input id="curriculumDictList{{idx}}_value" name="curriculumDictList[{{idx}}].value" type="text" value="{{row.value}}" maxlength="500" 
							class="input-small " style="width:200px;" />
						</td>
						<td>
							<input id="curriculumDictList{{idx}}_sort" name="curriculumDictList[{{idx}}].sort" type="text" value="{{row.sort}}" maxlength="10" 
							class="input-small  digits" style="width:50px;" />
						</td>
						<td>
							<!--<input id="curriculumDictList{{idx}}_status" name="curriculumDictList[{{idx}}].status" type="text" value="{{row.status}}" maxlength="3" 
							class="input-small  digits" style="width:50px;" />-->
							<select id="curriculumDictList{{idx}}_status" name="curriculumDictList[{{idx}}].status" 
							data-value="{{row.status}}" class="input-small ">
								<option value="">--请选择--</option>
								<option value="0">未启用</option>
								<option value="1">已启用</option>
								<option value="2">已废弃</option>
							</select>
						</td>
						
						<td>
							<input id="curriculumDictList{{idx}}_description" name="curriculumDictList[{{idx}}].description" type="text" value="{{row.description}}" maxlength="2000" 
							class="input-small " style="" />
						</td>
						<td>
							<input id="curriculumDictList{{idx}}_ext" name="curriculumDictList[{{idx}}].ext" type="text" value="{{row.ext}}" maxlength="2000" 
							class="input-small " style="" />
						</td>
						<td>
							<input id="curriculumDictList{{idx}}_remarks" name="curriculumDictList[{{idx}}].remarks" type="text" value="{{row.remarks}}" maxlength="1000" 
							class="input-small " style="" />
						</td>
						<td class="text-center">
							<a class="aBtn" href="javascript:void(0);" onclick="editCurriculumDictLine(this)">修改</a>
							<a class="aBtn" href="javascript:void(0);" onclick="delCurriculumDictLine(this)" name="deleteLine" name1="删除" name2="撤销">{{row.deleteOptName}}</a>
						</td>
					</tr>//-->
				</script>
				<script type="text/javascript">
					var curriculumDictRowIdx = 0 ;
					var curriculumDictTpl = $("#curriculumDictTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
					$(document).ready(function() {
						var data = ${fns:toJson(category.dictList)};
						jQuery('#curriculumDictList').children().remove();
						loadCurriculumDictListData(data);
					});
					function loadCurriculumDictListData(data){
						var len = jQuery('#curriculumDictList').children().length;
						for (var i=0; i<data.length; i++){
							var sort = (i+1)*10;
							//data[i].sort = sort;
							addRow('#curriculumDictList', curriculumDictRowIdx, curriculumDictTpl, data[i]);
							curriculumDictRowIdx = curriculumDictRowIdx + 1;
						}
					}
					function addCurriculumDictLine(){
						var data = [{}];
						loadCurriculumDictListData(data);
					}
					function delCurriculumDictLine(obj){
						if (obj != null) { //单个删除
							var curentTr = jQuery(obj).parents('tr')[0];
							var id = jQuery('[attrname="id"]', curentTr).val();
							delRow(curentTr);
						} else { //批量删除
							var table = jQuery('#curriculumDictList');
							var checkboxs = jQuery('input[attrname="sort"]:checked', table);
							if (checkboxs.length == 0) {
								alertx("请选择至少一行数据！");
								return;
							}
							var ids = [];
							for (var i = 0; i < checkboxs.length; i++) {
								var curentTr = jQuery(checkboxs[i]).parents('tr')[0];
								delRow(curentTr);
							}
						}
					}
				</script>
		  	</div>
		</div>
	</form:form>
	<div style="height: 50px;width: 100%;"></div>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			jQuery('#childTabs').children().each(function(){
				var refId = jQuery(this).attr('refId');
				jQuery(this).css('display','none');
				jQuery(this).children().remove();
				jQuery(this).append(jQuery('#'+refId).children());
			});
			jQuery('.tabli').click(function(){
				freshTabs(this);
			});
			freshTabs(jQuery('.tabli.active'));
			updatePageStatus();
		});
		
		function freshTabs(obj){ //切换页卡
			jQuery('.tabli').removeClass('active');
			 jQuery(obj).addClass('active');
			 var iframeId = jQuery(obj).attr('link');
			 jQuery('#childTabs').children().css('display','none');
			 jQuery('#'+iframeId).css('display','');
		}
		
		function addRow(list, idx, tpl, row){ //新增行
			if(row == null){ row = {};}
			if(row.index == null){ row.index = idx; }
			if(row.rowno == null){ row.rowno = idx+1; }
			row.deleteOptName = row.delFlag == "1"?"撤销":"删除";
			row.sort = row.rowno*10;
			$(list).append(Mustache.render(tpl, {
				idx: idx, delBtn: true, row: row
			}));
			$(list+idx).find("select").each(function(){
				$(this).val($(this).attr("data-value"));
				$(this).select2();
			});
			$(list+idx).find("input[type='checkbox'], input[type='radio']").each(function(){
				if($(this).attr("data-value") == null){
					return ;
				}
				var ss = $(this).attr("data-value").split(',');
				for (var i=0; i<ss.length; i++){
					if($(this).val() == ss[i]){
						$(this).attr("checked","checked");
					}
				}
			});
		}
		
		function delRow(curentTr){ //删除行
			var id = jQuery('[attrname="id"]', curentTr).val();
			var delFlag = jQuery(curentTr).find('[name*=".delFlag"]').val();
			if(id == null || id ==''){
				jQuery(curentTr).remove(); 
			}else if(delFlag == '1'){
				jQuery(curentTr).find('[name*=".delFlag"]').val(0);
				jQuery(curentTr).removeClass("error");
				jQuery(curentTr).find('[name="deleteLine"]').html('删除');
			}else {
				jQuery(curentTr).find('[name*=".delFlag"]').val(1);
				jQuery(curentTr).addClass("error");
				jQuery(curentTr).find('[name="deleteLine"]').html('撤销删除');
			}
			updateTrRowno(jQuery(curentTr).parents('tbody')[0]);
		}
		
		function updateTrRowno(tbody){ //更新行号
			jQuery(tbody).find('[attrname="number"]').each(function(i,v){
				jQuery(this).html(i+1);
			});
		}
	</script>
</body>
</html>